package com.glodon.zhuanli.common;

import com.glodon.framework.common.util.DTOUtil;
import com.glodon.framework.common.util.JsonMapper;
import com.glodon.framework.web.util.ResponseParam;
import com.glodon.infrastructure.rest.ErrorCode;
import com.glodon.infrastructure.support.DefaultBaseController;
import com.glodon.infrastructure.support.attachment.entity.Attachmentinfo;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(LocalFileController.BASEPATH)
public class LocalFileController extends DefaultBaseController {
	
	public static final String BASEPATH = "local" ;
	
	public static final String UPLOAD_FILE_PARAM = "file" ;
	
	@Autowired
	private LocalFileServiceImpl remoteFileService ;
	
	/**
	 * 查询结果要返回的字段
	 */
	private List<String> attachmentQueryResultFields =  Arrays.asList("id","oldname","filesize" ,"format","downloadNums") ;
	//图片格式的文件
	private Set<String> imageTypes = Sets.newHashSet( "png" , "jpg" , "jpeg" , "bmp") ;
	
	@RequestMapping(value="upload")
	@ResponseBody
	public String upload(MultipartRequest multipartRequest , 
			@RequestParam(value="type" , required = false)String type ,
			@RequestParam(value="businessid" , required=false) String businessid,@RequestParam(value="remark" , required=false) String remark) throws IOException{
		//获取上传文件
		MultipartFile multipartFile = multipartRequest.getFile( UPLOAD_FILE_PARAM ) ;
		String filename = multipartFile.getOriginalFilename() ;
		//上传文件
		Attachmentinfo attachmentinfo = remoteFileService.upload(multipartFile.getInputStream() , filename , type , businessid,remark) ;
		//返回文件名称
		Map<String, Object> result = new HashMap<String, Object>() ;
		result.put("realfilename", multipartFile.getOriginalFilename()) ;
		result.put("filename", attachmentinfo.getNewname()) ;
		result.put("attachmentinfoid", attachmentinfo.getId()) ;

		String downloadUrl = getDownloadUrl(attachmentinfo) ;

		result.put("fileurl" , downloadUrl) ;
		result.put("publicurl" ,downloadUrl ) ;

		return JsonMapper.toJSONString(result) ;
	}

	public String getDownloadUrl( Attachmentinfo attachmentinfo ){
		String downloadUrl = imageTypes.contains( StringUtils.removeStart(attachmentinfo.getFormat() , ".").toLowerCase() ) ?
				"/local/image/" : "/local/download/" ;

		downloadUrl += attachmentinfo.getOldname()+"?filepath="+attachmentinfo.getAttachment() ;

		return downloadUrl ;
	}

	@RequestMapping(value="ueditor/image/upload")
	@ResponseBody
	public String ueditorUpload(MultipartRequest multipartRequest) throws IOException{
		//ueditor文件上传对应的目录
		String type = "editor" ;
		//获取上传文件,ueditor图片上传的文件名参数为upfile
		MultipartFile multipartFile = multipartRequest.getFile("upfile") ;
		String filename = multipartFile.getOriginalFilename() ;
		//上传文件，设置ueditor上传文件的业务id为ueditor_upload
		Attachmentinfo attachmentinfo = remoteFileService.upload(multipartFile.getInputStream() , 
				filename , type , "ueditor_upload") ;
		//返回上传返回参数
		Map<String, Object> result = new HashMap<String, Object>() ;
		result.put("originalName", multipartFile.getOriginalFilename()) ;
		result.put("name", attachmentinfo.getNewname()) ;
		result.put("size", attachmentinfo.getFilesize()) ;
		result.put("state", "SUCCESS") ;
		result.put("type", attachmentinfo.getFormat()) ;
		//构建ueditor图片下载地址后缀
		//将ue地址更新为oss地址
		result.put("url" ,  attachmentinfo.getNewname()+"?type="+type) ;
		result.put("publicurl" , getDownloadUrl(attachmentinfo));
		//使用ueditor上传，返回转换后的字符串能够正常解析，否则报上传错误
		return JsonMapper.toJSONString(result) ;
	}

	/**
	 * 只提供一个根据文件路径下载文件的地址
	 * @param filepath
	 * @return
     */
	@RequestMapping("download/{filename}.{filesuffix}")
	public Object download(@RequestParam String filepath , @PathVariable String filename ,  @PathVariable String filesuffix) throws IOException {
		return download( filepath , filename+"."+filesuffix , MediaType.APPLICATION_OCTET_STREAM , "" ) ;
	}

	@Deprecated
	@RequestMapping("image/{filename}.{filesuffix}")
	public ResponseEntity<byte[]> downloadImg(@PathVariable("filename")String filename ,
											  @PathVariable("filesuffix")String filesuffix ,
											  @RequestParam(required=false , value="filepath") String filepath,
											  @RequestParam(value="type" , required = false) String type) throws IOException{
		return download( filepath , filename+"."+filesuffix , MediaType.IMAGE_JPEG , "" ) ;
	}

	/**
	 * 根据业务数据id获取附件列表
	 * @param businessid
	 * @return
	 */
	@RequestMapping(value="list/bybusiness/{businessid}" , method=RequestMethod.POST)
	@ResponseBody
	public ResponseParam getAttachmentListByBusinessId(@PathVariable String businessid){
		List<Attachmentinfo> attachmentinfos = attachmentinfoService.getAttachmentInfoList(businessid) ;
		//将Attachmentinfo转换为dto对象
		List<Map<String, Object>> attachmentList = DTOUtil.toDTO(attachmentinfos , attachmentQueryResultFields) ;

		return ResponseParam.success().addParam("attachmentinfos", attachmentList) ;
	}

	/**
	 * 保存上传附件文件的基本信息
	 * @param attachmentinfo
	 * @return
	 */
	@RequestMapping(value = "attachment/save",method = RequestMethod.POST)
	@ResponseBody
	public ResponseParam saveAttachmentInfo( Attachmentinfo attachmentinfo){
		if(StringUtils.isBlank(attachmentinfo.getAttachment())  || StringUtils.isBlank(attachmentinfo.getNewname())
				|| StringUtils.isBlank(attachmentinfo.getOldname())){
			return ResponseParam.fail().addCode(ErrorCode.OSS_ATTACHEMTN_SAVE_PARAM_ERROR.getCode()).addMessage(ErrorCode.OSS_ATTACHEMTN_SAVE_PARAM_ERROR.getRemark());
		}
		attachmentinfo.setDownloadNums(0l);//下载量默认值0
		attachmentinfo.setViewNums(0l);//浏览量默认值0
		attachmentinfoService.save(attachmentinfo);
		return ResponseParam.success();
	}

//	/**
//	 * 获取文件下载地址
//	 *     如: http://dasai.glodon.com.cn/get/url/test/a.jpg
//	 * @param type 文件类型     test
//	 * @param filePath 路径名称 a
//	 * @param filesuffix 后缀   jpg
//	 * @return
//	 */
//    @GetMapping(value = "get/url/{type}/{filepath}.{filesuffix}")
//    @ResponseBody
//    public String getOSSUrl(@PathVariable(value = "type") String  type,@PathVariable(value = "filepath") String filePath,@PathVariable(value = "filesuffix") String filesuffix){
//		String dir=remoteFileService.getFileDirectory(type);
//        return remoteFileService.getDownloadUrl(dir+"/"+filePath+"."+filesuffix);
//    }
//	@Deprecated
//	@RequestMapping("image/{filename}.{filesuffix}")
//	public ResponseEntity<byte[]> downloadImg(@PathVariable("filename")String filename ,
//			@PathVariable("filesuffix")String filesuffix ,
//			@RequestParam(required=false , value="realname") String realname,
//			@RequestParam(value="type" , required = false) String type) throws IOException{
//		String fullFileName = filename+"."+filesuffix ;
//		//在服务器缓存中缓存图片文件
//		File imageCacheFile = new File(System.getProperty("java.io.tmpdir")+getDownloadFilename(fullFileName)) ;
//		ResponseEntity<byte[]> responseEntity = null ;
//		//如果存在图片缓存则直接由缓存中下载图片，否则由ali下载图片
//		if(imageCacheFile.exists()){
//			responseEntity = ResponseEntity.ok(FileCopyUtils.copyToByteArray(imageCacheFile)) ;
//		}else{
//			responseEntity = download(fullFileName , realname ,  MediaType.IMAGE_JPEG , type) ;
//			if(responseEntity.getBody()!=null){
//				FileCopyUtils.copy(responseEntity.getBody(), imageCacheFile) ;
//			}
//		}
//
//		return responseEntity ;
//	}
//	@Deprecated
//	@RequestMapping(value = "file/{filename}.{filesuffix}" , method = RequestMethod.POST )
//	public ResponseEntity<byte[]> downloadFile(@PathVariable("filename")String filename ,
//			@PathVariable("filesuffix")String filesuffix ,
//			@RequestParam(required=false , value="realname") String realname,
//			@RequestParam(value="type" , required = false)String type) throws IOException{
//		String fullFileName = filename+"."+filesuffix ;
//
//		ResponseEntity<byte[]> responseEntity = download(fullFileName , realname , MediaType.APPLICATION_OCTET_STREAM, type) ;
//
//		return responseEntity ;
//	}
	/**
	 * 根据附件id下载附件信息
	 * @param attachmentInfoId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "file/byid/{attachmentinfoid}")
	public ResponseEntity<byte[]> downloadFileByAttachmentInfoId(
			@PathVariable("attachmentinfoid")String attachmentInfoId ) throws IOException{

		Attachmentinfo attachmentinfo = attachmentinfoService.get(attachmentInfoId) ;

		ResponseEntity<byte[]> responseEntity = null ;

		if(attachmentinfo!=null){
			responseEntity = download(attachmentinfo.getAttachment()  , attachmentinfo.getOldname() , MediaType.APPLICATION_OCTET_STREAM, attachmentinfo.getType()) ;
		}

		return responseEntity ;
	}
//
//	@Deprecated
//	@RequestMapping("image/byid/{attachmentinfoid}")
//	public ResponseEntity<byte[]> downloadImgByAttachmentId(
//			@PathVariable("attachmentinfoid")String attachmentInfoId) throws IOException{
//
//		//在服务器缓存中缓存图片文件
//		File imageCacheFile = new File(System.getProperty("java.io.tmpdir")+File.separator+"image_"+attachmentInfoId) ;
//		ResponseEntity<byte[]> responseEntity = null ;
//		//如果存在图片缓存则直接由缓存中下载图片，否则由ali下载图片
//		if(imageCacheFile.exists()){
//			responseEntity = ResponseEntity.ok(FileCopyUtils.copyToByteArray(imageCacheFile)) ;
//		}else{
//			Attachmentinfo attachmentinfo = attachmentinfoService.get(attachmentInfoId) ;
//
//			responseEntity = download(attachmentinfo.getNewname() , attachmentinfo.getOldname() ,
//					MediaType.IMAGE_JPEG , attachmentinfo.getType()) ;
//
//			if(responseEntity.getBody()!=null){
//				FileCopyUtils.copy(responseEntity.getBody(), imageCacheFile) ;
//			}
//		}
//
//		return responseEntity ;
//	}
	
	/**
	 * 下载文件
	 * @param fullfilename 完整的文件名，包括文件名称和路径
	 * @param mediaType 下载文件的类型
	 * @return
	 * @throws IOException
	 */
	public ResponseEntity<byte[]> download(String fullfilename , 
			String realFileName , MediaType mediaType , String type) throws IOException{
		
		fullfilename = getDownloadFilename(fullfilename) ;
		
		log.info("下载文件->"+fullfilename);
		
		byte[] bytes = remoteFileService.download(fullfilename , type) ;
		
		if(StringUtils.isNotBlank(realFileName)){
			String downLoadName = new String(realFileName.getBytes("GBK"), "iso8859-1");
			return ResponseEntity.status(HttpStatus.OK).contentType(mediaType).
				header(HttpHeaders.CONTENT_DISPOSITION , "attachment;fileName=" + downLoadName).
				body(bytes) ;
		}else{
			return ResponseEntity.status(HttpStatus.OK).contentType(mediaType).body(bytes) ;
		}
	}

	@Deprecated
	@RequestMapping("delete/{filename}.{filesuffix}")
	public void delete(@PathVariable("filename")String filename ,
			@PathVariable("filesuffix")String filesuffix, 
			@RequestParam(value="type" , required = false)String type) throws IOException{
		remoteFileService.delete(filename+"."+filesuffix , type) ;
	}
	/**
	 * 获取下载文件的真实名称
	 * @return
	 */
	public String getDownloadFilename(String fullfilename){
		//过滤.do名称
		if(StringUtils.isNotBlank(fullfilename)&&
				fullfilename.substring(fullfilename.length()-3).equals(".do")){
			fullfilename = fullfilename.substring(0, fullfilename.length()-3) ;
		}
		return fullfilename ;
	}
	
}
